package posecco.server;

import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpServletRequest;
import posecco.client.User;
import posecco.client.LoginService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {

	public String loginServer(String login, String password) throws IllegalArgumentException {
		// Verify that the input is valid. 
		try {
			ObjectifyService.register(User.class);
		}
		catch (IllegalArgumentException e) {}
        Objectify ofy = ObjectifyService.begin();
        User user = ofy.query(User.class).filter("loginLower", login.toLowerCase()).filter("password", password).get();
        try {
        	
            if (user != null) {
            	
            	try {
            		
             		HttpServletRequest request = getThreadLocalRequest();
            		HttpSession session = request.getSession();
            		String sessionID = session.getId();
               		user.setSessionId(sessionID);
            		ofy.put(user);
            		return sessionID;
            	}
            	catch (Exception e) {
            		
            		e.printStackTrace();
            	}
            	return null;
            }
            return null;
        }
        catch (NullPointerException e) {
        	
        	return null;
        }
	}

	public User getUserBySessionId(String sessionId)
			throws IllegalArgumentException {
		// TODO Auto-generated method stub
		try {
			ObjectifyService.register(User.class);
		}
		catch (IllegalArgumentException e) {}
        Objectify ofy = ObjectifyService.begin();
        User user = ofy.query(User.class).filter("sessionId", sessionId).get();
        try {
        	
            if (user != null) {
            	
            	return user;
            }
            return null;
        }
        catch (NullPointerException e) {
        	
        	return null;
        }
	}
	public User getUserById(Long id)
		throws IllegalArgumentException {
	// TODO Auto-generated method stub
		try {
			ObjectifyService.register(User.class);
		}
		catch (IllegalArgumentException e) {}
		Objectify ofy = ObjectifyService.begin();
		User user = ofy.query(User.class).filter("id", id).get();
		try {
			
		    if (user != null) {
		    	
		    	return user;
		    }
		    return null;
		}
		catch (NullPointerException e) {
			
			return null;
		}
	}
}
